package dao.impl;

import dao.UserDao;
import pojo.User;
import service.UserService;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class UserDaoImpl implements UserDao {
  //UserDao userDao=new UserDaoImpl();
  public List<User> findAll() {
    //jdbc操作
    List<User> users = new ArrayList<>();
    Connection connection = null;
    PreparedStatement preparedStatement= null;
    ResultSet resultSet = null;

    //jdbc操作数据库 查询

    try {

      // Scanner
      Scanner sc = new Scanner(System.in);
      System.out.print("请输入你要查询的姓名：");
      String word = sc.next();

      Class.forName("com.mysql.cj.jdbc.Driver");

      // 2、获取连接 (url username password)
      String url = "jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8";
       connection = DriverManager.getConnection(url, "root", "06060512han");

      // 3、写sql
      String sql = "select * from student where name like ? ";

      // 4、预编译sql
      preparedStatement = connection.prepareStatement(sql);

      // 5、有参数设置参数
      preparedStatement.setObject(1, "%" + word + "%");

      // 6、执行sql
       resultSet = preparedStatement.executeQuery();

      // 7、遍历结果集
      while (resultSet.next()) {
        User user = new User();
        user.setId(resultSet.getInt(1));
        user.setPass(resultSet.getString(3));
        user.setUsername(resultSet.getString(2));
        users.add(user);

        //System.out.println(id + "-----" + name + "------" + pass);
      }
      //返回集合
      return users;


    } catch (SQLException e) {
      throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
      throw new RuntimeException(e);
    }finally{
      //8关闭资源
      try {
        if(resultSet!=null)
          resultSet.close();
        if(preparedStatement!=null)
          preparedStatement.close();
        if(connection!=null)
          connection.close();
        return users;

      } catch (SQLException e) {
        throw new RuntimeException(e);
      }
      }
    }




  //  return users;
  }





